﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static ScannerApp.Common.Print32To63Link;

namespace ScannerApp.Common
{
 public   class Print32To63Link
    {

        [DllImport("User32.dll", EntryPoint = "SendMessage")]

        private static extern int SendMessage(

       IntPtr hWnd, // handle to destination window    

       int Msg, // message    

       int wParam, // first message parameter    

       ref COPYDATASTRUCT lParam // second message parameter    

       );


        [DllImport("User32.dll", EntryPoint = "FindWindow")]

        private static extern int FindWindow(string lpClassName, string

        lpWindowName);


        public struct COPYDATASTRUCT
        {

            public IntPtr dwData;

            public int cbData;

            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;

        }

        const int WM_COPYDATA = 0x004A;


        public static void OpenWindows()
        {
            bool IsExist = false;
            Process[] pros = Process.GetProcesses(); //获取本机所有进程
            for (int i = 0; i < pros.Length; i++)
            {
                if (pros[i].ProcessName == "Print32To64") //名称为ProcessCommunication的进程
                {
                    IsExist = true;
                    return;

                }

            }
            if (!IsExist)
            {
                string filePath = System.Environment.CurrentDirectory;

                string agentExe = filePath + "\\Print32To64.exe";

                var startInfo = new ProcessStartInfo(agentExe);
                var proc = Process.Start(startInfo);
                //int hWnd = FindWindow(null, @"Print32To64");
                
            }

        }

        public static void PipSocket(string Msg)
        {
            try
            {
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None))
                {
                    pipeClient.Connect(3000);//连接服务端
                    StreamWriter sw = new StreamWriter(pipeClient);
                    StreamReader sr = new StreamReader(pipeClient);
                    //while (true)
                    //{
                         
                        sw.WriteLine(Msg);
                        sw.Flush();

                       // var Result = sr.ReadLine();
                       // Console.WriteLine($"Reply:{Result}");
                   // }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
   
        public static void SendMessge(string sendString)
        {
            bool IsExist = false;
            Process[] pros = Process.GetProcesses(); //获取本机所有进程
            for (int i = 0; i < pros.Length; i++)
            {
                if (pros[i].ProcessName == "Print32To64") //名称为ProcessCommunication的进程
                {
                    IsExist = true;
                    IntPtr hWnd = pros[i].MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄
                    if (hWnd == IntPtr.Zero)
                        hWnd = pros[i].MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄

                     
                        byte[] sarr = System.Text.Encoding.Default.GetBytes(sendString);
                        int len = sarr.Length;
                      
                        COPYDATASTRUCT cds;
                        cds.dwData = (IntPtr)0;
                        cds.cbData = len + 1;
                        cds.lpData = sendString;
                     int rt=   SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
                    

                }

            }
            if (!IsExist)
            {
                string filePath = System.Environment.CurrentDirectory;

                string agentExe = filePath + "\\Print32To64.exe";

                var startInfo = new ProcessStartInfo(agentExe);
                var proc = Process.Start(startInfo);
                //int hWnd = FindWindow("Print32To64", null);
                byte[] sarr = System.Text.Encoding.Default.GetBytes(sendString);
                int len = sarr.Length;
                Thread.Sleep(1000);//启动后，等待一秒再发送
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)0;
                cds.cbData = len + 1;
                cds.lpData = sendString;
                  IntPtr hWnd = proc.MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄
                if (hWnd == IntPtr.Zero)
                    hWnd = proc.MainWindowHandle; //获取ProcessCommunication.exe主窗口句柄
                int data = Convert.ToInt32("0"); //获取文本框数据
                int rt = SendMessage(hWnd, WM_COPYDATA, 0, ref cds); //点击该按钮，以文本框数据为参数，向Form1发送WM_KEYDOWN消息

            }
        }

    }
}
